package portal;

import java.io.*;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.portlet.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import tavernacon.DataResource;
import tavernacon.DataValue;
import tavernacon.RESTClient;

public class Portal286 extends GenericPortlet {

    protected void doView(RenderRequest request, RenderResponse response)
            throws PortletException, IOException {
        /*see if a number is passed to the server as a parameter*/

        PortletSession session = request.getPortletSession();

        String workflow = request.getParameter("workflow");
        session.setAttribute("workflow", workflow);

        //if no number was entered, just show the form

        /*if (workflow.equals("Pollution")){
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.print("This is your " + workflow + " simualtion");
        out.print("<input type = \"text\"/><br/>");

        /*create a link back to the portlet using a PortletURL
        out.print("<A href=\"");
        out.print(response.createRenderURL());
        out.print("\">Try Again</A>");
        }*/

        /*if (inputKeys != null) {
        showInputs(request);
        }*/


        if (workflow == null) {
            String url = "/WEB-INF/jsp/workflowInterface.jsp";
            getPortletContext().getRequestDispatcher(url).include(request, response);
        } else {
            try {
                //runWorkflow(number);
                /*if a number was entered, display the correct answer*/
                /*response.setContentType("text/html");
                PrintWriter out = response.getWriter();
                out.print("You guessed " + number + workflow);
                out.print("<BR>The number was 5");
                out.print("<BR>Try again.");
                /*create a link back to the portlet using a PortletURL*
                out.print("<A href=\"");
                out.print(response.createRenderURL());
                out.print("\">Try Again</A>");
                if (workflow.equalsIgnoreCase("pollution")) {
                out.print("<%@ include file=\"UploadWorkflow_view.jsp\" %>");
                }*/
                createInterface(response, request);
            } catch (ParserConfigurationException ex) {
                Logger.getLogger(Portal286.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SAXException ex) {
                Logger.getLogger(Portal286.class.getName()).log(Level.SEVERE, null, ex);
            } catch (XPathExpressionException ex) {
                Logger.getLogger(Portal286.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void createInterface(RenderResponse response, RenderRequest request) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {

        PortletSession session = request.getPortletSession();
        String workflow = (String)session.getAttribute("workflow");

        DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
        Factory.setNamespaceAware(true);
        DocumentBuilder builder = Factory.newDocumentBuilder();
        Document doc = builder.parse("wf_data/" + workflow + ".xml");
        //creating an XPathFactory:
        XPathFactory factory = XPathFactory.newInstance();
        //using this factory to create an XPath object:
        XPath xpath = factory.newXPath();

        XPathExpression descExpr = xpath.compile("/workflow/description/text()");
        Object descResult = descExpr.evaluate(doc, XPathConstants.NODESET);
        NodeList descNodeList = (NodeList) descResult;

        XPathExpression typeExpr = xpath.compile("//inputs/input/type/text()");
        Object typeResult = typeExpr.evaluate(doc, XPathConstants.NODESET);
        NodeList typeNodeList = (NodeList) typeResult;

        XPathExpression nameExpr = xpath.compile("//inputs/input/name/text()");
        Object nameResult = nameExpr.evaluate(doc, XPathConstants.NODESET);
        NodeList nameNodeList = (NodeList) nameResult;

        XPathExpression exampleExpr = xpath.compile("//inputs/input/example/text()");
        Object exampleResult = exampleExpr.evaluate(doc, XPathConstants.NODESET);
        NodeList exampleNodeList = (NodeList) exampleResult;

        XPathExpression descriptionExpr = xpath.compile("//inputs/input/description/text()");
        Object descriptionResult = descriptionExpr.evaluate(doc, XPathConstants.NODESET);
        NodeList descriptionNodeList = (NodeList) descriptionResult;

        /*XPathExpression minExpr = xpath.compile("//inputs/input/restriction/min/text()");
        Object minResult = minExpr.evaluate(doc, XPathConstants.NODESET);
        NodeList minNodeList = (NodeList) minResult;

        XPathExpression maxExpr = xpath.compile("//inputs/input/restriction/max/text()");
        Object maxResult = maxExpr.evaluate(doc, XPathConstants.NODESET);
        NodeList maxNodeList = (NodeList) maxResult;

        InputValidator.setMin(minNodeList.item(0).getNodeValue());
        InputValidator.setMax(maxNodeList.item(0).getNodeValue());*/

        //looping through the xml interface doc
        String[] inputKeys = new String[typeNodeList.getLength()];

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        /*out.print("<%@page contentType=\"text/html\"%>" +
        "<%@page pageEncoding=\"UTF-8\"%>" +
        "<%@ page import=\"javax.portlet.*\"%>" +
        "<%@ taglib uri=\"http://java.sun.com/portlet_2_0\" prefix=\"portlet\"%>" +
        "<style type=\"text/css\">h1 {text-align:center;}r.title {color:#666666;}r.value {font-style:italic;color:#666666} table, td{border:0px solid black;}td{padding:3px;}</style>" +
        "<portlet:defineObjects />" +
        "<%PortletPreferences prefs = renderRequest.getPreferences();%>");*/
        out.print("<style type=\"text/css\">h1 {text-align:center;}r.title {color:#666666;}r.value {font-style:italic;color:#666666} table, td{border:0px solid black;}td{padding:3px;}</style>");
        out.print("<b>" + workflow + " Workflow</b>");
        out.print("<BR/><form method=\"post\" action=" + response.createActionURL() + ">");
        out.print("<table>");
        for (int i = 0; i < typeNodeList.getLength(); i++) {
            inputKeys[i] = nameNodeList.item(i).getNodeValue();
            out.print("<tr><td>" + nameNodeList.item(i).getNodeValue() + "</td><td><INPUT type=\"text\" name=\"" + nameNodeList.item(i).getNodeValue() + "\" size=\"20\"></td></tr>");
            out.print("<tr><td><r class=\"title\">Description</r></td>");
            out.print("<td><r class=\"value\">" + descriptionNodeList.item(i).getNodeValue() + "</r></td></tr>");
            out.print("<tr><td><r class=\"title\">Example</r></td>");
            out.print("<td><r class=\"value\">" + exampleNodeList.item(i).getNodeValue() + "</r></td></tr>");
        }
        out.print("</table><INPUT type=\"submit\" name=\"SUBMIT\" value=\"Run\">" +
                "</form>");

        /*create a link back to the portlet using a PortletURL*/
        out.print("<br/><A href=\"");
        out.print(response.createRenderURL());
        out.print("\">Select a different workflow</A>");

        session.setAttribute("inputKeys", inputKeys);
        System.out.println(inputKeys);
    }

    public void processAction(ActionRequest request, ActionResponse response) throws PortletException, java.io.IOException {

        runWorkflow(request);

    }

    public String runWorkflow(ActionRequest request) {

        
        System.out.println("run");

        PortletSession session = request.getPortletSession();

        String workflow = (String) session.getAttribute("workflow");
        String[] inputKeys = (String[]) session.getAttribute("inputKeys");

        System.out.println("Workflow: "+workflow);
        System.out.println("Keys: "+inputKeys);

        try {

            String[] inputValues = new String[inputKeys.length];
            for (int i = 0; i < inputKeys.length; i++) {
                inputValues[i] = request.getParameter(inputKeys[i]);
                //System.out.println("INPUT: " + input);
            }

            for (int i = 0; i < inputValues.length; i++) {
                System.out.println(inputKeys[i] + ": " + inputValues[i]);
            }

            DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
            Factory.setNamespaceAware(true);
            DocumentBuilder builder = Factory.newDocumentBuilder();
            Document doc = builder.parse("wf_data/" + workflow + ".xml");
            //creating an XPathFactory:
            XPathFactory factory = XPathFactory.newInstance();
            //using this factory to create an XPath object:
            XPath xpath = factory.newXPath();

            XPathExpression idExpr = xpath.compile("/workflow/idonserver/text()");
            Object idResult = idExpr.evaluate(doc, XPathConstants.NODESET);
            NodeList idNodeList = (NodeList) idResult;

            RESTClient tavernaRESTClient = new RESTClient();
            tavernaRESTClient.setBaseURL("http://localhost:9090/taverna-server-0.2.1/rest");

            Map<String, DataValue> ds = new HashMap<String, DataValue>();

            /*int noOfInputs = containerComponent.getChildren().size();

            for (int i = 0; i < noOfInputs; i = i + 6) {
            HtmlOutputText name = (HtmlOutputText) containerComponent.getChildren().get(i);//.getChildren().get(0);
            HtmlInputText in = (HtmlInputText) containerComponent.getChildren().get(i + 1);//.getChildren().get(1);
            //HtmlInputText hit = (HtmlInputText) obj;
            ds.put((String) name.getValue(), new DataValue((String) in.getValue()));

            String str = (String) name.getValue() + ", " + (String) in.getValue();
            System.out.println(str);
            }*/

            for (int i = 0; i < inputKeys.length; i++) {
                ds.put(inputKeys[i], new DataValue(inputValues[i]));
            }

            Long inputID = tavernaRESTClient.addData(new DataResource(ds));
            System.out.println("DataId :" + inputID);


            /*String workflowXML = IOUtils.toString(getClass().getResource("../test/pipeline.t2flow").openStream());
            Long workflowID = tavernaRESTClient.addWorkflow(workflowXML);
            System.out.println("WorkflowId :"+ workflowID);*/

            String wfidStr = idNodeList.item(0).getNodeValue();
            long wfid = Long.parseLong(wfidStr);
            long startTime = System.currentTimeMillis();
            long duration = 0;
            Long jobID = tavernaRESTClient.addJob(wfid, inputID);
            System.out.println("JobId :" + jobID);

        } catch (Exception e) {
        }
        return null;
    }
}
